package team.niit.bean;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import team.niit.service.UserService;
import team.niit.service.impl.UserServiceImpl;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

/**
 * @Author: 然然然儿呐_
 * @PackageName team.niit.bean
 * @Description: TO DO
 * @Date 2021/11/28 15:45
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@ManagedBean(name = "user")
@SessionScoped
public class UserBean {
    /**
     * 学号/工号
     */
    private String id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String gender;

    /**
     * 生日
     */
    private String birth;

    /**
     * 学院
     */
    private String school;

    /**
     * 专业
     */
    private String major;

    /**
     * 班级
     */
    private String classes;

    /**
     * 密码
     */
    private String password;

    /**
     * 手机号
     */
    private String phone;

    /**
     * 注册时候的第二个密码
     */
    private String newPassword;

    UserService userService = new UserServiceImpl();

    /**
     * 102：登录接口
     *
     * @return 跳转的页面
     */
    public String login() {
        Object userObject = userService.login(this.id, this.password);
        if (userObject != null) {
            BeanUtil.copyProperties(userObject, this);
            if (this.id.length() == 11) {
                if (this.password.equals(SecureUtil.md5("123456"))) {
                    return "init_password";
                } else {
                    return "index_student";
                }
            } else {
                return "index_admin";
            }
        } else {
            return "pages/error/failed_login";
        }
    }

    /**
     * 101：修改密码
     *
     * @return 返回成功与否
     */
    public String modifyPassword() {
        boolean flag = false;
        flag = userService.modifyPassword(this.id, this.password, this.newPassword);
        if (flag) {
            return "login";
        } else {
            return "pages/error/old_password_incorrect";
        }
    }

    /**
     * 103：重置密码/找回密码
     */
    public String retrievePassword() {
        boolean flag = false;
        flag = userService.retrievePassword(this.id, this.password, this.phone);
        if (flag) {
            return "login";
        } else {
            return "retrieve_password";
        }
    }

    public String initPassword() {
        boolean flag = false;
        flag = userService.initPassword(this.id, this.password);
        if (flag) {
            return "login";
        } else {
            return "init_password";
        }
    }

    public String modifyPWD() {
        this.password = "";
        this.newPassword = "";
        this.phone = "";
        return "modify_password";
    }

}
